package com.meichis.yndms.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.google.android.activity.TakePhotoActivity;
import com.google.android.entity.CameraParam;
import com.meichis.mcsappframework.entity.Attachment;
import com.meichis.mcsappframework.utils.DateUtil;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.yndms.R;
import com.meichis.yndms.adapter.ImageAdapter;
import com.meichis.yndms.common.GeoUtils;
import com.meichis.yndms.common.PictureUtils;
import com.meichis.yndms.databinding.ActivityVstVisitWorkItemJdBinding;
import com.meichis.yndms.model.Picture;
import com.meichis.yndms.room.AppDatabase;
import com.meichis.yndms.ui.common.BaseActivity;
import com.meichis.yndms.vm.VisitWorkItemJdVM;

import java.util.List;
import java.util.UUID;

public class VST_VisitWorkItem_JDActivity extends BaseActivity {

    private ActivityVstVisitWorkItemJdBinding binding;
    private VisitWorkItemJdVM vm;

    private static final int REQUEST_TAKEPHOTO = 0;
    private static final int MAXDISTANCE = 500;
    private static final int KEY_MARKER_CLIENT = 1;


    private ImageAdapter imageadapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding.VLocation.setUpMap(savedInstanceState);
        binding.VLocation.addMarker(vm.RT.getLatitude(), vm.RT.getLongitude(), BitmapDescriptorFactory.HUE_RED, KEY_MARKER_CLIENT);
    }

    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_vst_visit_work_item_jd);
        vm = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(VisitWorkItemJdVM.class);
        binding.setClick(new ClickEvent());
        binding.setLifecycleOwner(this);
    }

    @Override
    protected void init() {
        vm.setIntentData(getIntent());
        switch (vm.code) {
            case "JD":
                binding.navigation.txtTitle.setText("进店打卡");
                break;
            case "LD":
                binding.navigation.txtTitle.setText("离店拍照");
                break;
        }

        imageadapter = new ImageAdapter(this, R.layout.activity_signin_photoitem, vm.piclist);
        binding.rc.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        binding.rc.setAdapter(imageadapter);

        initEvents();
        addObserver();
    }

    private void addObserver() {
        vm.getShowDialog().observe(this, aBoolean -> showLoading(aBoolean));

        imageadapter.setonDeleteListener(position -> {
            binding.ibtTakephoto.setVisibility(vm.piclist.size() < 6 ? View.VISIBLE : View.GONE);
            vm.attlist.remove(position);
            return null;
        });

        vm.getWorkID().observe(this, workID -> {
            List<Picture> list = AppDatabase.getInstance().pictureDao().findPicByVisitGuid(vm.work.getGUID());
            for (Picture picture : list) {
                picture.setRelateID(workID);
                AppDatabase.getInstance().pictureDao().update(picture);
            }
            AppDatabase.getInstance().visitWorkItemDao().deleteAll(vm.work.getGUID());
            AppDatabase.getInstance().visitWorkDao().delete(vm.work);

            sendBroadcast(new Intent("com.meichis.yndms.intent.UpLoadInfo"));
            close();
        });

        vm.getJdComplate().observe(this, aBoolean -> {
            if (aBoolean) {
                showMsg("保存成功");
                setResult(RESULT_OK);
                close();
            }
        });

    }

    private void initEvents() {
        binding.navigation.navBack.setOnClickListener(v -> onBackPressed());

        binding.navigation.funBtn.setOnClickListener(v -> {
            //TODO:刷新的功能
//                ClientInfo clientInfo = AppDatabase.getInstance().clientInfoDao().find(vm.RT.getID());
//                if (clientInfo == null) {
//                    presenter.GetRetailerDetailInfo(0, vm.RT.getID());
//                } else {
//                    onReceiveRT(clientInfo);
//                }
        });
        binding.VLocation.setOnLocationChangedListener(aMapLocation -> {
            if (vm.needNewLocation) {
                vm.location = aMapLocation;
                if (TextUtils.isEmpty(vm.location.getAddress())) {
                    GeoUtils.GeoSearch(VST_VisitWorkItem_JDActivity.this, vm.location.getLatitude(), vm.location.getLongitude(), new GeoUtils.DecodeAddressListener() {
                        @Override
                        public void onRegeocodeAddress(String add, int state) {
                            vm.address = add;
                        }
                    });
                } else {
                    vm.address = vm.location.getAddress();
                }
                setRemark();
            }
            return null;
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        binding.VLocation.onResume();
    }

    protected void onPause() {
        super.onPause();
        binding.VLocation.onPause();
        binding.VLocation.deactivate();
    }

    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.VLocation.onSaveInstanceState(outState);
    }


    public class ClickEvent {

        public void onTakephoto() {
            if (vm.location == null) {
                showMsg("请稍后，定位中...");
                return;
            }
            Intent intent = new Intent(VST_VisitWorkItem_JDActivity.this, TakePhotoActivity.class);
            CameraParam takePhotoParam = new CameraParam(CameraParam.Quantity.Low);
            takePhotoParam.setWatermark("门店名称：" + vm.RT.getFullName()
                    + "\n" + "拍摄时间：" + DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS)
                    + "\n拍摄地址：" + vm.address
                    + "\n员工编码：" + vm.getUserInfo().getValue().getUsername()
                    + "\n员工姓名：" + vm.getUserInfo().getValue().getName());
            intent.putExtra("CameraParam", takePhotoParam);
            startActivityForResult(intent, REQUEST_TAKEPHOTO);
        }

        public void onSave() {
            if (vm.location == null) {
                showMsg("请稍后，定位中...");
                return;
            }
            if ("JD".equals(vm.code) && vm.piclist.size() == 0) {
                showMsg("至少拍一张照片");
                return;
            }

//            if (vm.location != null) {
//                if (vm.distance > MAXDISTANCE && (vm.code.equals("JD") || vm.code.equals("LD"))) {
//                    MessageTools.ShowmessageDialogYesOrNo(VST_VisitWorkItem_JDActivity.this, "进店打卡偏移距离大于500米，不允许拜访，请检查", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                        }
//                    }, (dialog, which) -> {
//
//                    });
//                    return;
//                }
//            }
            vm.save();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_CANCELED) return;
        switch (requestCode) {
            case REQUEST_TAKEPHOTO:
                String picPath = data.getExtras().getString("result");
                if (!TextUtils.isEmpty(picPath)) {
                    Picture pic = new Picture();
                    pic.setVisitGuid(vm.workGuid);
                    pic.setProcessCode(vm.code);
                    pic.setFilePath(picPath);
                    pic.setGuid(UUID.randomUUID().toString());
                    pic.setRelateType(4);//门店照片
                    pic.setFillName(picPath.substring(picPath.lastIndexOf("/") + 1));
                    AppDatabase.getInstance().pictureDao().insert(pic);
                    vm.piclist.add(pic);

                    Attachment att = new Attachment();
                    att.setGUID(pic.getGuid());
                    att.setExtName("jpg");
                    att.setAttName(pic.getFillName());
                    vm.attlist.add(att);
                }
                if (vm.piclist.size() >= 6)
                    binding.ibtTakephoto.setVisibility(View.GONE);
                imageadapter.notifyDataSetChanged();
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (vm.item == null)
            PictureUtils.deletePicture(vm.piclist);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.VLocation.Destroy();
    }

    private void setRemark() {
        if (vm.location == null)
            return;
        float[] result = new float[1];
        AMapLocation.distanceBetween(vm.RT.getLatitude(), vm.RT.getLongitude(), vm.location.getLatitude(), vm.location.getLongitude(), result);
        vm.remark = Math.round(result[0]) + "米";
        vm.distance = Math.round(result[0]);
        if (vm.RT.getLatitude() == 0 && vm.RT.getLongitude() == 0) {
            binding.VLocation.setRemark(VST_VisitWorkItem_JDActivity.this, "该门店没有上传标准位置");
        } else {
            if (Math.round(result[0]) > 800) {
                binding.VLocation.setRemark(VST_VisitWorkItem_JDActivity.this, "本次定位偏移" + vm.remark);
            } else {
                binding.VLocation.setRemark(VST_VisitWorkItem_JDActivity.this, "");
            }
            LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
            boundsBuilder.include(new LatLng(vm.RT.getLatitude(), vm.RT.getLongitude()));
            boundsBuilder.include(new LatLng(vm.location.getLatitude(), vm.location.getLongitude()));
            binding.VLocation.animateCamera(boundsBuilder);
        }
    }

}
